import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import {CacheService} from '@kylin/cache';
import {ConfigService} from '@kylin/config';
import {Observable} from 'rxjs';

@Injectable()
export class RequestInterceptor implements HttpInterceptor {

    hostname: string;

    constructor(private configService: ConfigService,
                private cacheService: CacheService) {
        this.hostname = this.configService.hostname;
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(this.defaultHeaders(req));
    }

    /**
     * 登陆接口不需要带Authorization,所以需要单独处理一下
     * @param req
     */
    private defaultHeaders(req: HttpRequest<any>) {
        if (req.url === '/login' || req.url === '/oauth/user/token') {
            return req.clone({
                url: this.handleReqUrl(req.url)
            });
        } else {
            const access_token = this.cacheService.get('access_token');
            return req.clone({
                url: this.handleReqUrl(req.url),
                setHeaders: {
                    'Authorization': `Bearer ${access_token}`
                }
            });
        }
    }

    private handleReqUrl(url: string): string {
        if (url.startsWith('http://')) {
            return url;
        } else {
            return this.hostname + url;
        }
    }
}

